package cyou.breathe.dynamictp.core.notification.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cyou.breathe.dynamictp.core.config.BootstrapConfigProperties;
import cyou.breathe.dynamictp.core.notification.dto.ThreadPoolAlarmNotifyDTO;
import cyou.breathe.dynamictp.core.notification.dto.ThreadPoolConfigChangeDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cyou.breathe.dynamictp.core.constant.Constants.LARK_ALARM_NOTIFY_MESSAGE_TEXT;
import static cyou.breathe.dynamictp.core.constant.Constants.LARK_CONFIG_CHANGE_MESSAGE_TEXT;

/**
 * @author: breathe
 * @createTime: 2025-09-15
 */
@Slf4j
public class LarkMessageService implements NotifierService {
    /**
     * 发送线程池配置变更通知到飞书机器人
     * @param configChangeDTO 配置变更信息
     */
    @Override
    public void sendChangeMessage(ThreadPoolConfigChangeDTO configChangeDTO) {
        Map<String, ThreadPoolConfigChangeDTO.ChangePair<?>> changes = configChangeDTO.getChanges();
        String markdownContent = String.format(
                LARK_CONFIG_CHANGE_MESSAGE_TEXT,
                configChangeDTO.getActive().toUpperCase(),
                configChangeDTO.getThreadPoolId(),
                configChangeDTO.getIdentify() + ":" + configChangeDTO.getApplicationName(),
                changes.get("corePoolSize").getBefore() + " ➲ " + changes.get("corePoolSize").getAfter(),
                changes.get("maximumPoolSize").getBefore() + " ➲ " + changes.get("maximumPoolSize").getAfter(),
                changes.get("keepAliveTime").getBefore() + " ➲ " + changes.get("keepAliveTime").getAfter(),
                configChangeDTO.getWorkQueue(),
                changes.get("queueCapacity").getBefore() + " ➲ " + changes.get("queueCapacity").getAfter(),
                changes.get("rejectedHandler").getBefore(),
                changes.get("rejectedHandler").getAfter(),
                configChangeDTO.getReceives(),
                configChangeDTO.getUpdateTime()
        );
        sendLarkMessage("线程池配置变更通知", markdownContent);
    }

    @Override
    public void sendAlarmMessage(ThreadPoolAlarmNotifyDTO alarmNotifyDTO) {

        String markdownText = String.format(
                LARK_ALARM_NOTIFY_MESSAGE_TEXT,
                alarmNotifyDTO.getActiveProfile().toUpperCase(),
                alarmNotifyDTO.getThreadPoolId(),
                alarmNotifyDTO.getIdentify() + ":" + alarmNotifyDTO.getApplicationName(),
                alarmNotifyDTO.getAlarmType(),
                alarmNotifyDTO.getCorePoolSize(),
                alarmNotifyDTO.getMaximumPoolSize(),
                alarmNotifyDTO.getCurrentPoolSize(),
                alarmNotifyDTO.getActivePoolSize(),
                alarmNotifyDTO.getLargestPoolSize(),
                alarmNotifyDTO.getCompletedTaskCount(),
                alarmNotifyDTO.getWorkQueueName(),
                alarmNotifyDTO.getWorkQueueCapacity(),
                alarmNotifyDTO.getWorkQueueSize(),
                alarmNotifyDTO.getWorkQueueCapacity() - alarmNotifyDTO.getWorkQueueSize(),
                alarmNotifyDTO.getRejectedHandlerName(),
                alarmNotifyDTO.getRejectCount(),
                alarmNotifyDTO.getReceives(),
                alarmNotifyDTO.getCurrentTime(),
                alarmNotifyDTO.getInterval()
        );
        sendLarkMessage("线程池告警通知", markdownText);
    }

    private void sendLarkMessage(String title, String markdownContent) {
        // 1. 创建最外层消息对象
        Map<String, Object> message = new HashMap<>();
        message.put("msg_type", "post");

        // 2. 创建content对象
        Map<String, Object> content = new HashMap<>();

        // 3. 创建post对象
        Map<String, Object> post = new HashMap<>();

        // 4. 创建中文内容对象
        Map<String, Object> zhCn = new HashMap<>();
        zhCn.put("title", title);

        List<List<Map<String, Object>>> contentList = new ArrayList<>();
        List<Map<String, Object>> firstLine = new ArrayList<>();
        Map<String, Object> textElement = new HashMap<>();
        textElement.put("tag", "text");
        textElement.put("text", markdownContent);
        firstLine.add(textElement);
        contentList.add(firstLine);

        // 8. 组装完整结构
        zhCn.put("content", contentList);
        post.put("zh_cn", zhCn);
        content.put("post", post);
        message.put("content", content);

        // 9. 发送请求
        try {
            String serverUrl = BootstrapConfigProperties.getInstance().getNotifyPlatforms().getUrl();
            String responseBody = HttpUtil.post(serverUrl, JSONObject.toJSONString(message));
            LarkRobotResponse response = JSON.parseObject(responseBody, LarkRobotResponse.class);
            if (response.getCode() != 0) {
                log.error("飞书消息发送失败, 原因是: {}", response.msg);
            }
        } catch (Exception ex) {
            log.error("飞书消息发送失败, 原因是: {}", ex);
        }
    }

    @Data
    static class LarkRobotResponse {
        private Long code;
        private String msg;
    }
}
